local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.Server_PlayerComponent());
local function_list = ServerOHOH.function_list;
local Badge_Cfg=ServerOHOH.config.Badge
local ItemTool=_G.CommonOHOH.load.ItemTool();
local BadgeService = game:GetService("BadgeService")

--添加徽章
function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
    M.super.ctor(self, parent);

    self.DataBase=self.parent:GetComponent(ServerOHOH.load.Server_PlayerDataComponent())
    self.OldLevel=self.DataBase:GetData("base").level
    self.HasBadge={}
    self.parent.UserDataEvent:Connect(function(key)
        if key=="base"  then
            local level=self.DataBase:GetData("base").level
            if level>self.OldLevel then
                for k,v in pairs(Badge_Cfg) do
                    if level>v.condition then
                        self:AddBadge(k)
                    end
                end
                self.OldLevel=level
            end

        end
    end)

    self:AddProcess(function()
        self:Wait(15)
        for k,v in pairs(Badge_Cfg) do
            if self.OldLevel>v.condition then
                self:AddBadge(k)
                self:Wait(2)
            end
        end
    end)

end;

function M.AddBadge(self,id)

    -- print("AddBadge----0>",id)

    local badgeId=Badge_Cfg[id].rid
    assert(badgeId,"badgeId==1")
    if self.HasBadge[badgeId] then
        return
    end

    self:AddProcess(function()
    -- print("AddBadge----1>",id)
    -- print("AddBadge----1.1>",self.parent:GetUserId(),badgeId)

        local success, hasBadge = pcall(function()
            return BadgeService:UserHasBadgeAsync(self.parent:GetUserId(), badgeId)
        end)

        -- 如果发生错误，则发出警告并退出该函数
        if not success then
            -- print("AddBadge----2>",hasBadge)

            return 
        end

        if hasBadge then
            -- print("AddBadge----3>",id)

            self.HasBadge[badgeId]=true
            return 
        else
            -- print("AddBadge----4>",id)

            BadgeService:AwardBadge(self.parent:GetUserId(), badgeId)
            self.HasBadge[badgeId]=true
        end
    end)
end

function M.dtor(self)
	M.super.dtor(self);
end;

return M